package netty.rpc.core;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 序列化器
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2022/5/10 23:39
 */
public class HessianSerialization {

    /**
     * rpc 请求 序列化成字节数组
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
        hessianOutput.writeObject(object);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        return bytes;
    }

    public static Object deserialize(byte[] bytes,Class clazz) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        HessianInput hessianInput = new HessianInput(byteArrayInputStream);
        Object object = hessianInput.readObject(clazz);
        return object;
    }

}
